package com.crr.service.impl;

import com.crr.bean.Order;
import com.crr.bean.OrderDetail;
import com.crr.common.utils.Assert;
import com.crr.common.utils.RabbitUtils;
import com.crr.common.utils.RedisUtils;
import com.crr.mapper.GoodsMapper;
import com.crr.mapper.OrderDetailMapper;
import com.crr.mapper.OrderMapper;
import com.crr.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    RedisUtils redisUtils;
    @Autowired
    RabbitUtils rabbitUtils;
    @Autowired
    OrderMapper orderMapper;
    @Autowired
    GoodsMapper goodsMapper;
    @Autowired
    OrderDetailMapper orderDetailMapper;

    @Transactional
    @Override
    public int saveOrder(Order order) {
        if (null == order.getOrderNum()) {
      //普通订单 生成订单编号
        }
        //保存订单
        int res = orderMapper.save(order);
        Assert.isNotSuccess(res, "生成订单失败");
        if (null != order.getOrderDetails() && order.getOrderDetails().size() > 0) {
            //保存订单明细
            res = orderDetailMapper.batchSave(order.getId(), order.getOrderDetails());
            Assert.isNotSuccess(res, "生成订单明细失败");
            //更新库存 发送mq消息到 库存队列
            //遍历订单详情表
            Iterator<OrderDetail> it = order.getOrderDetails().iterator();
            while (it.hasNext()) {
                OrderDetail next = it.next();
                res = goodsMapper.updateStock(next.getGoodsId(), next.getNum());
                Assert.isNotSuccess(res, "更新库存失败");
            }
        }
        //一分钟未支付 取消订单
        rabbitUtils.sendLazy(order.getId() + "");
        redisUtils.del("user:id:" + order.getUserId());
        return 1;
    }

    @Override
    public int updateStatus(int id) {
        return orderMapper.updateStatus(id);
    }

    @Override
    public Order getOrder(String orderNum) {
        return orderMapper.getOrder(orderNum);
    }

    @Override
    public String save(int userId, int goodsId) {
        //得到用户id
        String userKey = "user:id:" + userId;
        //判断用户是否已经抢购 nx存在则不能写入返回0
        boolean flag = redisUtils.setNx(userKey, goodsId + "");
        if (!flag) {
            //说明已经抢购过
            return redisUtils.get(userKey);
        }
        String key = "goods:id:" + goodsId;
        //尝试扣减库存
        List<String> keys = new ArrayList<>();
        keys.add(key);
        Long stock = redisUtils.eval(getLua(), keys);
        if (stock == 0) {
            System.out.println(userId + "抢购失败，库存剩余" + stock);
            return null;//抢购失败
        }
        System.out.println("用户" + userId + "抢购第" + stock + "台成功");
        //记录当前用户抢购成功
        redisUtils.set(userKey, goodsId + "");
        String orderNum = "MSDD2024102601";
        redisUtils.set(userKey, orderNum);
        //
        rabbitUtils.send1(userId + "@" + goodsId + "@" + orderNum);
        return orderNum;//抢购成功
    }


    String getLua() {
        StringBuilder lua = new StringBuilder();
        lua.append("local stock=tonumber(redis.call('get',KEYS[1]))");
        lua.append("    if (stock == 0) then");
        lua.append("        return 0;");
        lua.append("    end;");
        lua.append("    if (stock > 0) then");
        lua.append("        redis.call('decr', KEYS[1]);");
        lua.append("        return stock;");
        lua.append("    end;");
        return lua.toString();
    }

}
